package gorm.springboot.demo.controllers

import gorm.springboot.demo.model.Person
import gorm.springboot.demo.services.PersonService
import groovy.util.logging.Slf4j
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.*

@RestController()
@RequestMapping("/person")
@Slf4j
@Transactional
class PersonController {

    @Autowired
    PersonService personService

    /**
     * 查询一个Person
     * @param id
     * @return
     */

    @GetMapping(value = "/person/{id}")
    def getPersonById(@PathVariable("id") Long id) {
        return [msg: "success", data: personService.findById(id).firstName]

    }
    /**
     * 添加一个Person
     * @param lastName
     * @param firstName
     * @return
     */

    @PutMapping(value = "/addPerson")
    def addPerson(@RequestParam String lastName, @RequestParam String firstName) {
        Person person = new Person(firstName: firstName, lastName: lastName)
        personService.save(person)
        return [msg: "success"]


    }

    /**
     * PersonList
     * @return
     */
    @GetMapping(value = "/personList", produces = "application/json")
    def personList() {
        return [msg: "success", data: personService.findAll().size()]

    }

    @PostMapping(value = "/search")
    def search(@RequestBody Map map) {
        Person person = personService.search(map)
        if (person){
            return [msg: "success", data: [lastName: person.lastName, firstName: person.firstName, id: person.id]]

        }else {
            return [msg: "Empty data"]
        }

    }

}
